package com.XinYun.Library.utils.EmailUtil;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.UUID;

public class EmailUtil {
    public static String giveRcode(String mail) throws Exception {
        Properties prop = new Properties();
        prop.setProperty("mail.host","smtp.qq.com");
        //设置qq邮件服务器
        prop.setProperty("mail.transport.protocol","smtp");
        //邮件发送协议
        prop.setProperty("mail.smtp.auth","true");
        //需要验证密码
        //关于qq邮箱，还要设置SSL加密，加上以下代码即可
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable","true");
        prop.put("mail.smtp.ssl.socketFactory",sf);
        //使用java mail 发送邮件的五个步骤
        //1.创建定义整个应用程序所需要的环境信息的session 对象
        // qq才有！
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //发件人的邮件用户名、授权码
                return new PasswordAuthentication("xinyun2023library@163.com", "DILLVYSQHDJIVTEA");
            }
        });
        //开启debug
        session.setDebug(true);
        //2.通过session得到transport 对象
        Transport ts = session.getTransport();
        //3.通过邮箱的用户名和授权码连上邮件服务器
        ts.connect("smtp.qq.com","xinyun2023library@163.com","DILLVYSQHDJIVTEA");
        //4.创建邮件:
        MimeMessage message = new MimeMessage(session);
        //指明发件人
        message.setFrom(new InternetAddress("xinyun2023library@163.com"));
        //指明邮件的收件人，现在的发件人和收件人一样，= 给自己发
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(mail));
        //邮件主题
        message.setSubject("www.XinYunLibrary.com验证码");
        String rcode = UUID.randomUUID().toString();
        //邮件内容
        message.setContent("您好验证码是:"+rcode,"text/html;charset=UTF-8");
        //5.发送邮件
        ts.sendMessage(message,message.getAllRecipients());
        //6.关闭连接
        ts.close();


        return rcode;
    }



}
